package com.yy.base.common.action;

import com.mes.entity.User;
import com.yy.base.util.UserUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class BaseCtrl implements ServletContextAware {
	protected final transient Log logger = LogFactory.getLog(getClass());

	private ServletContext servletContext;
	
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	protected ServletContext getServletContext() {
		return servletContext;
	}

	/**
	 * 获取当前系统时间
	 */
	protected Date getNowDate() {
		return new Date();
	}

	//处理空字符，前后空格
	protected String isNull(String str) {
		if (str == null) {
			return null;
		}
		return str.trim();
	}

	protected User getLoginUser(HttpServletRequest request) {
		return UserUtil.getLoginUser(request);
	}
	
	/**
	 * 将请求参数转换为Map对象
	 */
	@SuppressWarnings("unchecked")
	protected Map<String, Object> getParameterMap(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String[]> paramMap = request.getParameterMap();
		for (String name : paramMap.keySet()) {
			map.put(name, paramMap.get(name)[0]);
		}
		return map;
	}
	
	protected String getRemortIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}
}
